import {type Options } from "./type"
import Delete from './delete'

export default class extends Delete {
    constructor(options: Options){
        super(options)
    }

    private colIndex: number = -1
    private startX: number = -1
    private startWidth: number = 0
    private minWidth: number = 0

    private doResize () {
        if (this.colIndex !== -1) {
          const deltaX = event.clientX - this.startX;
          let newWidth = this.startWidth + deltaX;

          if(newWidth < this.minWidth) return

          this.columns.value[this.colIndex].width = newWidth + 'px';
        }
    }
    private stopResize() {
        this.colIndex = -1;
        document.removeEventListener('mousemove', this.doResize);
        document.removeEventListener('mouseup', this.stopResize);
    }
    startResize (index: number) {
        this.colIndex = index;
        this.startX = event?.clientX;

        const currentColumn = this.getCellElement({colindex: this.colIndex});
        if(!currentColumn) return;
        
        this.startWidth = parseInt(getComputedStyle(currentColumn).width)
        this.minWidth = parseInt(getComputedStyle(currentColumn.querySelector('.th-cell')).width)
        const doResize = () => this.doResize()
        const stopResize = () => this.stopResize()
        document.addEventListener('mousemove', doResize)
        document.addEventListener('mouseup', stopResize);
    }

    getThWidth (colIndex: number) {
        const th = this.columns?.value[colIndex]
        return typeof th.width === 'number' ? th.width + 'px' : th.width
    }

}